package com.easy.component.network.request;

import com.easy.component.network.utils.NetWorkLogger;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * 描述: {描述}
 * 作者:jack-song
 * 创建日期: 2017/9/28 14:32
 * 修改日期: 2017/9/28
 * 版本: {版本}
 */
public abstract class BaseBodyRequest<T extends BaseBodyRequest> extends BaseRequest<T> {
    /**
     * 发送纯文本
     */
    private String string;
    /**
     * 发送json
     */
    private String json;
    /**
     * form表单专用
     */
    public Map<String, Object> parameterForm;

    public BaseBodyRequest(String url) {
        super(url);
    }

    public T setString(String string) {
        this.string = string;
        return (T) this;
    }

    public T setJson(String json) {
        this.json = json;
        return (T) this;
    }
    public T setParameterForm(Map<String, Object> parameterForm) {
        this.parameterForm = parameterForm;
        return (T) this;
    }

    public Call<ResponseBody> executeRequest(int method) {
        if (null != string) {
            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/plain; charset=utf-8"), getUrlParams(string));
            return (method == Method.POST) ? apiManager.postBody(url+ "?"+getUrlParams(string)) : apiManager.getBody(url + "?"+getUrlParams(string));
        } else if (null != json) {
            NetWorkLogger.i("ResponseBody", "---responseBody--->" + json);
            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), this.json);
            return (method == Method.POST) ? apiManager.postJson(url, body) : apiManager.getBody(url);
        }
        return null;
    }

    private String getUrlParams(String json) {
        StringBuilder result = new StringBuilder();
        try {
            if (null != json) {
                boolean isFirst = true;
                Map<String, Object> objectMap = new Gson().fromJson(json, Map.class);
                for (Map.Entry<String, Object> entry : objectMap.entrySet()) {
                    if (!isFirst) {
                        result.append("&");
                    } else {
                        isFirst = false;
                    }
                    result.append(entry.getKey()).append("=").append(entry.getValue());
                }
            }
        } catch (Exception e) {

        }
        return result.toString();
    }

}
